<template>
    <el-breadcrumb separator="/" id="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/home/system' }">系统设置</el-breadcrumb-item>
        <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <tableList
            :dict="dict"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @doit="tableDoit"
    />
    <drawer
            :dict="dict"
            :drawerData="drawerData"
            :drawerConfig="drawerConfig"
            @doit="drawerDoit"
    />
    <deleteDialog
        :deleteDialogConfig="deleteDialogConfig"
    />
</template>

<script setup lang="ts">
import tableList from '@/components/TableList.vue'
import drawer from '@/components/Drawer.vue'
import deleteDialog from '@/components/DeleteDialog.vue'
import {ref, reactive, onMounted} from 'vue'
import {addRole, delRole, editRole, getRoleList, getRoleMenuTreeselect} from "@/api/system/role.ts";
import {createDict} from "@/common/dict.ts";
import {ElMessage} from 'element-plus'

//table
import {table_config} from './tableConfig.js'

let tableConfig:any= reactive(table_config()) //表格配置
let tableData:any = ref([]) //表格数据
let search:any = reactive({})
//drawer
import {drawer_config} from './drawerConfig.js'


let drawerConfig:any = reactive(drawer_config()) //抽屉配置
// const thing:any = { //新建的实体
//   "remark": "",
//   "roleId": null,
//   "roleName": "",
//   "roleKey": "",
//   "roleSort": "1",
//   "menuCheckStrictly": '1',
//   "deptCheckStrictly": '1',
//   "status": "0",
//   "menuIds": [],
//   "deptIds": [],
// }
// {"roleName":"111","roleKey":"222","roleSort":333,"status":"0","menuIds":[],"deptIds":[],"menuCheckStrictly":true,"deptCheckStrictly":true}
let drawerData:any = ref({})
let deleteDialogConfig:any = ref({
    visible: false,
    message: "是否删除",
    alertTitle:"警告",
    confirmText: "确认",
    cancelText: "取消",
    confirmFunction: () => {
    },
    cancelFunction: () => {
    }
}) //删除对话框配置
const dictKey:Array<string> = ['sys_normal_disable'] //本页面所需要的字典值
let dict:any = reactive({})

onMounted(async () => {
    dict = await createDict(dictKey) //模块字典值初始化
    await dataInit() //数据初始化
})

//数据初始化
async function dataInit() {
    //分页数据加载
    let page = {
        pageNum: tableConfig.pageNum,
        pageSize: tableConfig.pageSize
    }
    let data = Object.assign(page, search)
    //数据初始化
    const r = await getRoleList(data)
    tableData.value = r.data
    tableConfig.total = r.total
    //格式化添加修改的表单数据
    drawerConfig.form[1].options = tableData.value
}
let selection = [] //多选的数据
//table事件调度中心
async function tableDoit(e) {
    const eventName = e.eventName, val = e.value
  // @ts-ignore
    tell.log('表格事件分析', eventName, val)
    let rs, tmpVal
    switch (eventName) {
        case 'refresh': //数据重新加载
            await dataInit()
            break;
        case 'expand': //展开或回收列表
            tableConfig.defaultExpandAll = !tableConfig.defaultExpandAll
            break;
        case 'add': //新增数据
            tmpVal = Object.assign({}, val) //深度复制，防止污染
            rs = await getRoleMenuTreeselect()
            drawerConfig.form[8].options = rs.menus
            tmpVal.menuIds = []
            drawerData.value = tmpVal
            drawerConfig.show = true
            break;
        case 'edit': //编辑数据
            tmpVal = Object.assign({}, val) //深度复制，防止污染
            //获取菜单权限
            rs = await getRoleMenuTreeselect(val.roleId)
            console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>',rs)
            drawerConfig.form[8].options = rs.menus

          tmpVal.menuIds = rs.checkedKeys
          tmpVal.menuIds.push(0)
          tmpVal.menuIds.pop()
          console.log(tmpVal.menuIds, typeof tmpVal.menuIds)
          console.log(rs.checkedKeys)
            drawerData.value = tmpVal
            drawerConfig.show = true
            break;
        case 'selectionChange': //批量选择
            selection = val
            break;
        case 'delAll':
            if (selection.length > 0){
                deleteDialogConfig.value = {
                    visible: true,
                    message: "是否批量删除选择的数据。请再次确认！",
                    alertTitle:"警告",
                    confirmText: "确认",
                    cancelText: "取消",
                    confirmFunction: async () => {
                        for(let i in selection){
                            await delRole(selection[i]['roleId'])
                        }
                        deleteDialogConfig.value.visible = false
                        await dataInit()
                        ElMessage({
                            message: '删除成功，用户功能待用户刷新后才能正常使用.',
                            type: 'success',
                        })
                    },
                }
            }
            break;
        case 'delete': //删除
            deleteDialogConfig.value = {
                visible: true,
                message: "是否删除，删除后无法恢复数据。请再次确认！",
                alertTitle:"警告",
                confirmText: "确认",
                cancelText: "取消",
                confirmFunction: async () => {
                    let result = await delRole(val.roleId)
                    if (result.code == 200){
                        await dataInit()
                        ElMessage({
                            message: '删除成功，用户功能待用户刷新后才能正常使用.',
                            type: 'success',
                        })
                        deleteDialogConfig.value.visible = false
                    }else{
                        ElMessage({
                            message: '数据错误，请管理员查看问题',
                            type: 'warning',
                        })
                    }
                },
            }
            break;
        case 'search': //搜索
            search = val
            await dataInit()
            break;
        case 'handleSizeChange':
            tableConfig.pageSize = val
          await dataInit()
            break
        case 'handleCurrentChange': //点击分页
            tableConfig.pageNum = val
          await dataInit()
            break
        default:
          // @ts-ignore
            tell.log('未知组件事件', eventName, val)
    }
}

//drawer事件调度中心
async function drawerDoit(e) {
    const eventName = e.eventName, val = e.value
  // @ts-ignore
    tell.log('抽屉事件分析', eventName, val)
    switch (eventName) {
        case 'save': //保存数据
            let result:any = ""
            if (val.roleId){
              console.log('val', val)
              result = await editRole(val)
            }else{
              delete val.roleId
              result = await addRole(val)
            }

            if (result.code == 200){
                await dataInit()
                ElMessage({
                    message: '新增成功',
                    type: 'success',
                })
                drawerConfig.show = false
            }else{
                ElMessage({
                    message: '数据错误，请管理员查看问题',
                    type: 'warning',
                })
            }

            break;
        case 'close': //关闭弹窗
            drawerConfig.show = false
            break;
        default:
          // @ts-ignore
            tell.log('未知组件事件', eventName, val)
    }
}
</script>
<style scoped lang="scss">
.content {
  padding-top: 20px;
}
</style>